﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CodeBox.FB.DataAccess;
using CodeBox.FB.ViewModels;
using System.Data.Objects.SqlClient;
namespace CodeBox.FB.DataAccess
{

    public class TeamDataAccess
    {
        OritiaDataContext dataContext;
        public IEnumerable<TeamViewModel> TeamsList()
        {
            dataContext = new OritiaDataContext();
            var allteams = from teams in dataContext.Teams
                           select new TeamViewModel { ID = teams.ID, TeamName = teams.TeamName, ImageUrl = teams.ImageUrl };
            return allteams.AsEnumerable<TeamViewModel>();

        }

        public TeamInfoModel TeamInfo(string teamName)
        {
            dataContext = new OritiaDataContext();
            var teamInfo = dataContext.Teams.Single(x => x.TeamName == teamName);
            return new TeamInfoModel()
            {
                ID = teamInfo.ID,
                Average = ((decimal)(teamInfo.Average ?? 0)),
                ImageUrl = teamInfo.ImageUrl,
                Lost = ((int)(teamInfo.Lost ?? 0)),
                Matches = teamInfo.Matches,
                NoResult = ((int)(teamInfo.NoResult ?? 0)),
                Points = teamInfo.Points,
                TeamName = teamInfo.TeamName,
                Tied = ((int)(teamInfo.Tied ?? 0)),
                Won = ((int)(teamInfo.Won ?? 0))
            };
        }


        public List<PlayerViewModel> Players(string teamName, int seasonID)
        {
            dataContext = new OritiaDataContext();
            var teamInfo = dataContext.Teams.Single(x => x.TeamName == teamName);
            var players = (from crew in dataContext.Crews
                           join player in dataContext.Players on crew.ID equals player.CrewId
                           join PTS in dataContext.PlayerTeamSeasons on player.ID equals PTS.PlayerId
                           where PTS.Team.ID == teamInfo.ID && PTS.Season.ID == seasonID
                           group crew by new { crew.ID, crew.Name, crew.Photo } into grp
                           select new PlayerViewModel { playerID = (int)grp.Key.ID, Name = grp.Key.Name, imageUrl = grp.Key.Photo });
            return players.AsEnumerable<PlayerViewModel>().ToList();
        }

        public Boolean Update(TeamInfoModel team)
        {
            dataContext = new OritiaDataContext();
            Team teams = new Team();
            teams.TeamName = team.TeamName;
            teams.ImageUrl = team.ImageUrl;
            teams.Points = 0;
            teams.Matches = 0;
            dataContext.AddObject("Team", teams);
            dataContext.AcceptAllChanges();
            return true;
        }
    }
}
